<template>
  <div class="p-2">
    <div class="flex items-center">
<!--      <el-input v-model="workUrl" placeholder="请输入小红书作品地址" class="w-600px" clearable></el-input>-->
      <el-input v-model="shareText" placeholder="请输入小红书分享链接" class="w-600px" clearable></el-input>
<!--      <el-button @click="test222" class="ml-2">小红书</el-button>-->
      <el-button @click="getWorkInfo" class="ml-2">获取作品信息</el-button>
    </div>
    <div class="h-520px w-full mt-2">
      <div class="p-2 border-2">
        <div v-if="Object.keys(workInfo).length > 0" class="flex">
          <div class="w-260px">
            <img :src="workInfo?.image_list[0]?.url_default" alt="" class="w-250px h-333px rounded-[16px]">
            <div class="text-15px mt-2 leading-20px text-[#333333]">{{workInfo?.title}}</div>
            <div class="flex items-center">
              <img :src="workInfo?.user?.avatar" class="w-24px h-24px rounded-full mr-2" alt="">
              <div class="text-15px text-[#5c5c5c]">{{workInfo?.user?.nickname}}</div>
            </div>
          </div>
          <div class="w-500px text-14px leading-18px space-y-3">
            <div class="flex">
              <div class="">笔记内容：</div>
              <div class="text-left w-360px">{{workInfo?.desc}}</div>
            </div>
            <div class="flex">
              <div>发布时间：</div>
              <div>{{formatTimestamp(workInfo.time)}}</div>
            </div>
            <div class="flex">
              <div>笔记ID：</div>
              <div>{{workInfo.note_id}}</div>
            </div>
            <div class="flex">
              <div>点赞数：</div>
              <div>{{workInfo.interact_info.liked_count}}</div>
            </div>
            <div class="flex">
              <div>评论数：</div>
              <div>{{workInfo.interact_info.comment_count}}</div>
            </div>
            <div class="flex">
              <div>收藏数：</div>
              <div>{{workInfo.interact_info.collected_count}}</div>
            </div>
            <div class="flex">
              <div>分享数：</div>
              <div>{{workInfo.interact_info.share_count}}</div>
            </div>
            <div class="flex">
              <div>笔记图片数：</div>
              <div>{{workInfo.image_list.length}}</div>
            </div>
            <div class="flex items-center">
              <el-button @click="downloadImg">下载图片</el-button>
              <div class="ml-2">下载进度：{{downloadSucceedList.length}}/{{workInfo.image_list.length}}</div>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>
<script setup>
import {ipc} from "@/utils/ipcRenderer";
import {ipcApiRoute} from "@/api";
import {ref} from "vue";
import {formatTimestamp} from "@/utils/format";
import modal from "@/utils/modal";
import axios from "axios";

const workUrl = ref('')
const shareText = ref('')

const workInfo = ref({})

const downloadSucceedList = ref([])

// 监听下载进度
ipc.on('controller/download/downloadFile/progress', (event, result) => {
  downloadSucceedList.value = result.list
  console.log('下载进度更新：', downloadSucceedList.value)
  // if (downloadSucceedList.value.length === workInfo.value.image_list.length) {
  //   modal.msgSuccess('下载完成')
  // }
})

const test111 = async() => {
  console.log('点击了点我')
  const res = await ipc.invoke(ipcApiRoute.request.node_request, {
    method: "GET",
    url: 'https://www.baidu.com'
  })
  console.log('res:', res)
}

const test222 = async () => {
  const res = await ipc.invoke(ipcApiRoute.xhs.getWorkInfo, {
    workId: '67526dc00000000007030413',
    xsecToken: 'ABnySTssUDZ0Zmlc7vTUVL__bLzw7gLaYIIU9AnRByzVY'
  })
  console.log('res:', res)
  workInfo.value = res.data.items[0].note_card
  console.log('workInfo:', workInfo.value)
}

const getWorkInfo = async () => {
  downloadSucceedList.value = []

  // 定义正则表达式，用于匹配 URL
  const urlRegex = /https?:\/\/[^\s,，]+/;
  const match = shareText.value.match(urlRegex);
  const extractUrl = match ? match[0] : null;
  console.log('正则地址：', extractUrl);

  if (shareText.value === '') {
    modal.msgWarning('请输入分享链接')
  }
  console.log('shareText:', shareText.value)

  const res = await ipc.invoke(ipcApiRoute.xhs.linkRestoration, {
    url: extractUrl
  })
  console.log("短链还原结果:", JSON.parse(res))
  // 创建 DOMParser 实例
  const parser = new DOMParser();
  // 解析 HTML 字符串为 Document 对象
  const doc = parser.parseFromString(JSON.parse(res), 'text/html');
  // 提取链接地址
  const linkElement = doc.querySelector('a');
  const link = linkElement ? linkElement.href : '';
  console.log('提取后的链接地址:', link)

  // 创建 URL 对象
  const urlObj = new URL(link);
  // 提取作品 ID
  const pathSegments = urlObj.pathname.split('/');
  const workId = pathSegments[pathSegments.length - 1];
  // 提取 xsec_token 的值
  const searchParams = new URLSearchParams(urlObj.search);
  const xsecToken = searchParams.get('xsec_token');
  // 输出结果
  console.log('作品 ID:', workId);
  console.log('xsec_token 的值:', xsecToken);

  const getWorkInfoRes = await ipc.invoke(ipcApiRoute.xhs.getWorkInfo, {
    workId: workId,
    xsecToken: xsecToken
  })
  console.log('getWorkInfoRes:', getWorkInfoRes)
  workInfo.value = getWorkInfoRes.data.items[0].note_card
  console.log('workInfo:', workInfo.value)
}

const downloadImg = async () => {
  let imgUrlList = workInfo.value.image_list.map(item => item.url_default)
  console.log('下载图片：', imgUrlList)
  let files = imgUrlList.map(item => {
    return {
      url: item,
      directory: 'C:\\Users\\92183\\Desktop\\测试'
    }
  })
  console.log('files:', files)

  await ipc.invoke(ipcApiRoute.download.downloadFile, {
    files: files
  })
}

</script>
<style scoped>

</style>
  